<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\View;
use think\facade\Validate;
use app\common\model\WechatKeywords as WechatKeywordsModel;
use app\common\model\WechatTemplate as WechatTemplateModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\CompanyContent as CompanyContentModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\WechatTweetsTpl as WechatTweetsTplModel;
use app\common\model\Files as FilesModel;
use app\bsadmin\model\ApiApp as ApiAppModel;
use app\common\controller\Posters as PostersController;
use app\common\controller\Vip as VipController;
use helper\URL;
use helper\Wechat as WechatHelper;
class Wechat extends Base
{
    public function menu()
    {
        $Data=config('xy_wechat_mp_menu');
        $D=[];
        if(!empty($Data['button'])){
            foreach ($Data['button'] as $k => $v) {
                if (empty($v['sub_button'])) {
                    $D[$k]=[
                        'title'     => $v['name'],
                        'type'      => $v['type'],
                        'data'      =>  [],
                    ];
                    switch ($v['type']) {
                        case 'key':
                            $D[$k]['content']=$v['key'];
                            break;
                        case 'click':
                            $D[$k]['content']=$v['key'];
                            break;
                        case 'miniprogram':
                            $D[$k]['content']='';
                            $D[$k]['url']=$v['url'];
                            $D[$k]['appid']=$v['appid'];
                            $D[$k]['pagepath']=$v['pagepath'];
                            break;
                        
                        default:
                            $D[$k]['content']=$v['url'];
                            break;
                    }
                }else{
                    $D[$k]=[
                        'title'     => $v['name'],
                        'type'      => 'view',
                        'content'   => 'sub',
                    ];
                    foreach ($v['sub_button'] as $ke => $va) {
                        $D[$k]['data'][$ke]=[
                            'title'     => $va['name'],
                            'type'      => $va['type'],
                            ];
                        switch ($va['type']) {
                            case 'key':
                                $D[$k]['data'][$ke]['content']=$va['key'];
                                break;
                            case 'click':
                                $D[$k]['data'][$ke]['content']=$va['key'];
                                break;
                            case 'miniprogram':
                                $D[$k]['data'][$ke]['content']='';
                                $D[$k]['data'][$ke]['url']=$va['url'];
                                $D[$k]['data'][$ke]['appid']=$va['appid'];
                                $D[$k]['data'][$ke]['pagepath']=$va['pagepath'];
                                break;
                            
                            default:
                                $D[$k]['data'][$ke]['content']=$va['url'];
                                break;
                        }
                    }
                }
            }
        }
        View::assign('wxmenu',$D);
        return View::fetch();
    }
    public function saveMenu()
    {
        if (request()->isPost()) {
            $D=request()->post();
            if(empty($D['menu']))return $this->ajaxReturn('菜单不能为空');
            $RouteWrite="<?php\nreturn [\n'button'=>[";
            $menus='';
            foreach ($D['menu'] as $k => $v) {
                if(empty($v['data'])){
                    switch ($v['type']) {
                        case 'key':
                            $content="'key'=>'".$v['content']."'";
                            break;
                        case 'click':
                            $content="'key'=>'".$v['content']."'";
                            break;
                        case 'miniprogram':
                            $content="'url'=>'".$v['url']."'";
                            $content.=",'appid'=>'".$v['appid']."'";
                            $content.=",'pagepath'=>'".$v['pagepath']."'";
                            break;
                        
                        default:
                            $content="'url'=>'".$v['content']."'";
                            break;
                    }
                    $menus.=$k."=>['name'=>'".$v['title']."','type'=>'".$v['type']."',".$content."],\n";
                }else{
                    $menus.=$k."=>['name'=>'".$v['title']."','sub_button'=>[";
                    foreach ($v['data'] as $ke => $va) {
                        switch ($va['type']) {
                            case 'key':
                                $content="'key'=>'".$va['content']."'";
                                break;
                            case 'click':
                                $content="'key'=>'".$va['content']."'";
                                break;
                            case 'miniprogram':
                                $content="'url'=>'".$va['url']."'";
                                $content.=",'appid'=>'".$va['appid']."'";
                                $content.=",'pagepath'=>'".$va['pagepath']."'";
                                break;
                            
                            default:
                                $content="'url'=>'".$va['content']."'";
                                break;
                        }
                        $menus.=$ke."=>['name'=>'".$va['title']."','type'=>'".$va['type']."',".$content."],\n";
                    }
                    $menus.="],],";

                }
            }
            $RouteWrite.=$menus."]];";
            $RoutePath=config_path()."xy_wechat_mp_menu.php";;
            $RouteFile = fopen($RoutePath, "w") or die("Unable to open file!");
            fwrite($RouteFile, $RouteWrite);
            fclose($RouteFile);
            return $this->ajaxReturn();
        }
    }
    public function releaseMenu()
    {
        if(request()->isAjax()){
            $Data=config('xy_wechat_mp_menu');
            // JSON转换并且中文不转换
            $menus = json_encode($Data, JSON_UNESCAPED_UNICODE);
            // 获取TOKEN
            try {
                $token = WechatHelper::GetWeiXinToken();
            } catch (\think\Exception $e) {
                return $this->ajaxReturn($e->getMessage(),-100);
            }
            if (empty($token))
                return $this->ajaxReturn('非常抱歉，TOKEN获取失败',-100);
            if (!empty($token['status']) && $token['status']){
                $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$token['access_token']}";
                // 创建菜单
                $status = json_decode(URL::post($url, $menus), true);
                if ($status['errcode'] == 0 && $status['errmsg'] == 'ok') {
                    return $this->ajaxReturn('发布微信菜单成功');
                }else{
                    return $this->ajaxReturn('发布微信菜单失败<br />错误码：' . $status['errcode']. '<br />错误信息：' . $status['errmsg'],-100);
                }
            }else{
                return $this->ajaxReturn('非常抱歉，TOKEN获取失败',-100);
            }
        }
    }
    public function keywords()
    {
        if (request()->isAjax()) {
            $Data=WechatKeywordsModel::order('id desc')->paginate(1000)->each(function($v){
                switch ($v->type) {
                    case 'image':
                    case 'video':
                        $FilesModel=FilesModel::where(['media_id'=>$v->value])->find();
                        if ($FilesModel)
                        $v->url=config('web.imgurl').$FilesModel->path;
                        break;
                }
                return $v;
            });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑套餐
     */
    public function editKeywords($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'keyword'       => 'require|max:20',
                'value'         => 'require',
            ];
            $msg  =   [
                'keyword.require'       => '关键词不能为空', 
                'keyword.max'           => '关键词不能超过20个字符',
                'value.require'         => '请输入或选择回复内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatKeywordsModel=WechatKeywordsModel::find($id);
            $WechatKeywordsModel->keyword       = $D['keyword'];
            $WechatKeywordsModel->value         = $D['value'];
            $WechatKeywordsModel->type          = $D['type'];
            $WechatKeywordsModel->status        = $D['status'];
            $WechatKeywordsModel->is_default    = $D['is_default'];
            if ($D['is_default']&&WechatKeywordsModel::where(['is_default'=>1])->whereNotIn('id',[$id])->count())
                $this->cancelKeywordsDefault();
            $this->setKeywordsCache($WechatKeywordsModel);
            if ($WechatKeywordsModel->save()) {
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=WechatKeywordsModel::where(['id'=>$id])->find();
            if (request()->isAjax())
                return $this->ajaxReturn('',0,$Find);
            View::assign('Find',$Find);
            return View::fetch('add_keywords');
        }
    }
    /**
     * 创建套餐
     */
    public function addKeywords()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'keyword'       => 'require|max:20',
                'value'         => 'require',
            ];
            $msg  =   [
                'keyword.require'       => '关键词不能为空', 
                'keyword.max'           => '关键词不能超过20个字符',
                'value.require'         => '请输入或选择回复内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatKeywordsModel=new WechatKeywordsModel;
            $WechatKeywordsModel->keyword       = $D['keyword'];
            $WechatKeywordsModel->value         = $D['value'];
            $WechatKeywordsModel->type          = $D['type'];
            $WechatKeywordsModel->status        = $D['status'];
            $WechatKeywordsModel->is_default    = $D['is_default'];
            if ($D['is_default'])
                $this->cancelKeywordsDefault();
            $this->setKeywordsCache($WechatKeywordsModel);
            if ($WechatKeywordsModel->save()) {
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setKeywordsStatus($id,$status)
    {
        $WechatKeywordsModel=WechatKeywordsModel::find($id);
        $WechatKeywordsModel->status=$status;
        $this->setKeywordsCache($WechatKeywordsModel);
        if ($WechatKeywordsModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 设置套餐状态
     */
    public function setKeywordsDefault($id,$default)
    {
        $WechatKeywordsModel=WechatKeywordsModel::find($id);
        $WechatKeywordsModel->is_default=$default;
        $this->cancelKeywordsDefault();
        if ($WechatKeywordsModel->save()) {
            $this->setKeywordsCache($WechatKeywordsModel);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function cancelKeywordsDefault()
    {
        $DefaultWechatKeywordsModel=WechatKeywordsModel::where(['is_default'=>1])->find();
        if ($DefaultWechatKeywordsModel) {
            $DefaultWechatKeywordsModel->is_default=0;
            $DefaultWechatKeywordsModel->save();
        }
    }
    public function setKeywordsCache($Model)
    {
        /*if ($Model->status) {
            if ($Model->is_default)
                Cache::set('Wechat.default.keywords',$Model->value);
            Cache::set('Wechat.keywords.'.$Model->keyword,$Model->value);
        }else{
            if ($Model->is_default)
                Cache::delete('Wechat.default.keywords');
            Cache::delete('Wechat.keywords.'.$Model->keyword);
        }*/
    }
    public function delKeywords($id)
    {
        $WechatKeywordsModel=WechatKeywordsModel::find($id);
        $WechatKeywordsModel->status=0;
        $WechatKeywordsModel->is_default=0;
        $this->setKeywordsCache($WechatKeywordsModel);
        if ($WechatKeywordsModel->delete()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function pushTpl()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if(!empty($G['action'])&&$G['action']=='cache'){
                $WechatTemplateModel=WechatTemplateModel::field('id')->select();
                foreach ($WechatTemplateModel as $v) {
                    $this->setPushTplCache($v->id);
                }
                return $this->ajaxReturn();
            }
            $Data=WechatTemplateModel::paginate(1000)->each(function($v){
                    $v->item_data=json_decode($v->item_data,true);
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑套餐
     */
    public function editPushTpl($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'alias'       => 'require|max:50|unique:wechat_template',
                'title'       => 'require|max:100',
                'tplid'       => 'require',
                'first'       => 'require',
                'remark'      => 'require',
            ];
            $msg  =   [
                'alias.require'       => 'Alias不能为空', 
                'alias.max'           => 'Alias不能超过50个字符',
                'alias.unique'        => 'Alias已存在',
                'title.require'       => '名称不能为空',
                'title.max'           => '名称不能超过100个字符',
                'tplid.require'       => '模板ID不能为空',
                'first.require'       => 'First不能为空',
                'remark.require'      => 'Remark不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatTemplateModel=WechatTemplateModel::find($id);
            $alias='';
            if($WechatTemplateModel->alias!=$D['alias'])
                $alias=$WechatTemplateModel->alias;
            $WechatTemplateModel->alias         = $D['alias'];
            $WechatTemplateModel->number        = $D['number'];
            $WechatTemplateModel->title         = $D['title'];
            $WechatTemplateModel->tplid         = $D['tplid'];
            $WechatTemplateModel->first         = $D['first'];
            $WechatTemplateModel->first_color   = empty($D['first_color'])?'#343434':$D['first_color'];
            $WechatTemplateModel->remark        = $D['remark'];
            $WechatTemplateModel->remark_color  = empty($D['remark_color'])?'#343434':$D['remark_color'];
            $WechatTemplateModel->item_data     = json_encode($D['item_data'],JSON_UNESCAPED_UNICODE);
            $WechatTemplateModel->url           = $D['url'];
            $WechatTemplateModel->status        = $D['status'];
            if ($WechatTemplateModel->save()) {
                if($alias)
                $this->delPushTplCache($alias);
                $this->setPushTplCache($WechatTemplateModel->id);
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=WechatTemplateModel::where(['id'=>$id])->withAttr('item_data',function($v,$data){
                return json_decode($v,true);
            })->find();
            if (request()->isAjax())
                return $this->ajaxReturn('',0,$Find);
            View::assign('Find',$Find);
            return View::fetch('add_push_tpl');
        }
    }
    /**
     * 创建套餐
     */
    public function addPushTpl()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'alias'       => 'require|max:50|unique:wechat_template',
                'title'       => 'require|max:100',
                'tplid'       => 'require',
                'first'       => 'require',
                'remark'      => 'require',
            ];
            $msg  =   [
                'alias.require'       => 'Alias不能为空', 
                'alias.max'           => 'Alias不能超过50个字符',
                'alias.unique'        => 'Alias已存在',
                'title.require'       => '名称不能为空',
                'title.max'           => '名称不能超过100个字符',
                'tplid.require'       => '模板ID不能为空',
                'first.require'       => 'First不能为空',
                'remark.require'      => 'Remark不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatTemplateModel=new WechatTemplateModel;
            $WechatTemplateModel->alias         = $D['alias'];
            $WechatTemplateModel->number        = $D['number'];
            $WechatTemplateModel->title         = $D['title'];
            $WechatTemplateModel->tplid         = $D['tplid'];
            $WechatTemplateModel->first         = $D['first'];
            $WechatTemplateModel->first_color   = empty($D['first_color'])?'#343434':$D['first_color'];
            $WechatTemplateModel->remark        = $D['remark'];
            $WechatTemplateModel->remark_color  = empty($D['remark_color'])?'#343434':$D['remark_color'];
            $WechatTemplateModel->item_data     = json_encode($D['item_data'],JSON_UNESCAPED_UNICODE);
            $WechatTemplateModel->url           = $D['url'];
            $WechatTemplateModel->status        = $D['status'];
            if ($WechatTemplateModel->save()) {
                $this->setPushTplCache($WechatTemplateModel->id);
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setPushTplStatus($id,$status)
    {
        $WechatTemplateModel=WechatTemplateModel::find($id);
        $WechatTemplateModel->status=$status;
        if ($WechatTemplateModel->save()) {
            $this->setPushTplCache($id);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function setPushTplCache($id)
    {
        /*$WechatTemplateModel=WechatTemplateModel::where(['id'=>$id])->withAttr('item_data',function($v){
            return json_decode($v,true);
        })->find();
        if ($WechatTemplateModel)
            Cache::set('WechatTemplate.'.$WechatTemplateModel->alias,$WechatTemplateModel->toArray());*/
    }
    /**
     * 设置套餐状态
     */
    public function delPushTpl($id)
    {
        $WechatTemplateModel=WechatTemplateModel::find($id);
        if ($WechatTemplateModel->delete()) {
            $this->delPushTplCache($WechatTemplateModel->alias);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function delPushTplCache($alias)
    {
        // Cache::delete('WechatTemplate.'.$alias);
    }
    public function tweets()
    {
        if(request()->post()){
            $D=request()->post();
            switch ($D['type']) {
                case 'jobs':
                    $JobsModel=$this->getJobsList($D);
                    if($JobsModel)
                        return $this->ajaxReturn('',0,$JobsModel);
                    return $this->ajaxReturn('未检索到数据',-100);
                case 'company':
                    $CompanyModel=$this->getCompanyList($D);
                    if($CompanyModel)
                        return $this->ajaxReturn('',0,$CompanyModel);
                    return $this->ajaxReturn('未检索到数据',-100);
            }
        }else{
            $arealist=Cache::get('arealist');
            View::assign('arealist',$arealist);
            $ApiAppModel=ApiAppModel::where('app_modul','in',['index','appapiv1','mobile','wechatminiprogram'])->field('app_id,app_name')->select();
            if($ApiAppModel)
            View::assign('ClientApp',$ApiAppModel->toArray());
            $VipController=VipController::getCate();
            View::assign('vip',$VipController);
            return View::fetch();
        }
    }
    public function community_tweets()
    {
        if(request()->post()){
            $D=request()->post();
            switch ($D['type']) {
                case 'jobs':
                    $JobsModel=$this->getJobsList($D);
                    if($JobsModel)
                        return $this->ajaxReturn('',0,$JobsModel);
                    return $this->ajaxReturn('未检索到数据',-100);
                case 'company':
                    $CompanyModel=$this->getCompanyList($D);
                    if($CompanyModel)
                        return $this->ajaxReturn('',0,$CompanyModel);
                    return $this->ajaxReturn('未检索到数据',-100);
                case 'saveTpl':
                    if (empty($D['tpl_name'])) {
                        return $this->ajaxReturn('模板名称不能为空',-100);
                    }
                    if (empty($D['tpl_content'])) {
                        return $this->ajaxReturn('模板内容不能为空',-100);
                    }
                    $WechatTweetsTplModel=null;
                    if(!empty($D['id']))
                        $WechatTweetsTplModel=WechatTweetsTplModel::where(['id'=>$D['id']])->find();
                    if(!$WechatTweetsTplModel)
                        $WechatTweetsTplModel=new WechatTweetsTplModel;
                    $WechatTweetsTplModel->tpl_type=$D['tpl_type'];
                    $WechatTweetsTplModel->tpl_name=$D['tpl_name'];
                    $WechatTweetsTplModel->tpl_content=$D['tpl_content'];
                    if($WechatTweetsTplModel->save()){
                        return $this->ajaxReturn('保存成功');
                    }else{
                        return $this->ajaxReturn('保存失败，请重试',-100);
                    }
                    break;
            }
        }else{
            $arealist=Cache::get('arealist');
            View::assign('arealist',$arealist);
            $ApiAppModel=ApiAppModel::where('app_modul','in',['index','appapiv1','mobile','wechatminiprogram'])->field('app_id,app_name')->select();
            if($ApiAppModel)
            View::assign('ClientApp',$ApiAppModel->toArray());
            $WechatTweetsTplModel=WechatTweetsTplModel::select();
            if($WechatTweetsTplModel)
            View::assign('tplData',$WechatTweetsTplModel->toArray());
            $VipController=VipController::getCate();
            View::assign('vip',$VipController);
            return View::fetch();
        }
    }
    public function getCompanyList($D)
    {
        $where=[];
        if(!empty($D['app_id'])){
            $where[]=['c.app_id','in',$D['app_id']];
        }
        if(!empty($D['area'])){
            if(!empty($D['area'][0]))
            $where[]=['content.contacts_area2','=',intval($D['area'][0])];
            if(!empty($D['area'][1]))
            $where[]=['content.contacts_area1','=',intval($D['area'][1])];
            if(!empty($D['area'][2]))
            $where[]=['content.contacts_area3','=',intval($D['area'][2])];
        }
        if (!empty($D['company_id']))
            $where[]=['c.id','=',intval($D['company_id'])];
        if (!empty($D['industry']) && $D['industry'])
            $where[]=['c.industry_id','=',intval($D['industry'])];
        if (!empty($D['size_type']) && $D['size_type'])
            $where[]=['c.size_type','=',intval($D['size_type'])];
        if (!empty($D['finance']) && $D['finance'])
            $where[]=['c.finance','=',intval($D['finance'])];
        if (!empty($D['is_famous']) && $D['is_famous']!=0)
            $where[]=['c.is_famous','=',intval($D['is_famous'])];
        if (!empty($D['vip_level']))
            $where[]=['user_vip.company_vip_level','in',$D['vip_level']];
        $sort='c.is_famous desc,c.attestation desc,c.refresh_time desc,c.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='c.refresh_time desc,c.id desc';
                    break;
                case 'recommend':
                    $sort='c.refresh_time desc,c.id desc';
                    break;
                case 'rand':
                    $sort='c.refresh_time desc,c.id rand()';
                    break;
            }
        }
        $Field=[
            'c.id,c.title,c.stitle,c.logo,c.corporate_welfare,c.view',
            'industry.title as industry',
            'size_type.title as size_type',
            'content.contacts,content.contacts_mobile,content.contacts_address,content.company_introduction',
            'province.title as province,city.title as city,area.title as area',
            'nature.title as nature',
            'finance.title as finance'
        ];
        $qrsize=new \stdClass;
        $qrsize->size=140;
        if(config('xy_company.is_forceattestation'))
        $where[]=['c.attestation','=',3];
        $CompanyModel=CompanyModel::alias('c')
            ->where(['user.status'=>1])
            ->where($where);
            if(!empty($D['time'])&&count($D['time'])===2){
                $CompanyModel->whereTime('c.create_time','between',[$D['time'][0]/1000,$D['time'][1]/1000]);
            }

            //TODO 需要修改条件
         $subSelect=JobsModel::alias('jobs')
            ->where('jobs.status',1)
             ->whereNull('jobs.delete_time')
            ->where(['education.alias'=>'jobs/education_level'])
            ->where(['exp_level.alias'=>'jobs/exp_level'])
            ->join('status_alias education','education.value=jobs.education_level')
            ->join('status_alias exp_level','exp_level.value=jobs.exp_level')
             ->group('jobs.company_id')
             ->column('jobs.company_id');
        $Data=$CompanyModel->where(['size_type.alias'=>'company/size_type'])
            ->where(['nature.alias'=>'company/nature'])
            ->where(['finance.alias'=>'company/finance'])
            ->whereIn('c.id',$subSelect)
            ->join('user user','user.id=c.uid')
            ->join('user_vip user_vip','user_vip.uid=c.uid')
            ->join('company_content content','content.cid=c.id')
            ->join('company_industry industry','industry.id=c.industry_id')
            ->join('status_alias size_type','size_type.value=c.size_type')
            ->join('status_alias nature','nature.value=c.nature')
            ->join('status_alias finance','finance.value=c.finance')
            ->join('area city','city.id = content.contacts_area1')
            ->join('area province','province.id = content.contacts_area2')
            ->join('area area','area.id = content.contacts_area3')
            ->order($sort)
            ->field(implode(",",$Field))->paginate($D['sum'])
            ->each(function($item, $key)use($qrsize){
                $item->showjobs=1;
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
                $JobsModel=JobsModel::alias('jobs')->where(['jobs.company_id'=>$item['id'],'jobs.status'=>1])
                    ->whereNull('jobs.delete_time')
                    ->where(['education.alias'=>'jobs/education_level'])
                    ->where(['exp_level.alias'=>'jobs/exp_level'])
                    ->join('status_alias education','education.value=jobs.education_level')
                    ->join('status_alias exp_level','exp_level.value=jobs.exp_level');
                if(config('xy_company.jobs_view_status'))
                    $JobsModel->where(['jobs.examine'=>1]);
                $item['jobs']=$JobsModel->field('jobs.id,jobs.title,jobs.status,jobs.salary_min,jobs.salary_max,jobs.salary_year,jobs.number_of_recruiters,education.title as education,exp_level.title as exp_level')->select();
//                $item['jobs']=$JobsModel->field('jobs.id,jobs.title,jobs.status,jobs.salary_min,jobs.salary_max,jobs.salary_year,jobs.number_of_recruiters')->select();
                $item['jobs_sum']=$JobsModel->count();
                $item->welfare=$item['corporate_welfare']?StatusAliasModel::where(['alias'=>'company/corporate_welfare'])->where('value','in',explode(',',$item['corporate_welfare']))->column('title'):[];
                $qrcode=PostersController::CreateCompanyQRCode($item,$qrsize);
                if($qrcode)
                $item->qrcode=config('web.imgurl').$qrcode;
                $item['logo']=$item['logo']?config('web.imgurl').$item['logo']:config('web.imgurl').config('xy_default_avatar.company_logo');
                return $item;
            });
        return $Data;
    }
    public function getJobsList($D)
    {
        $where=[];
        if (!empty($D['jobs_cid'])){
            $cid1=[];
            $cid2=[];
            $cid3=[];
            foreach ($D['jobs_cid'] as $k => $v) {
                if(!in_array($v[0], $cid1))
                    $cid1[]=$v[0];
                if(!in_array($v[1], $cid2))
                    $cid2[]=$v[1];
                $cid3[]=$v[2];
            }
            $where[]=['jobs.jobs_cate1','in',$cid1];
            $where[]=['jobs.jobs_cate2','in',$cid2];
            $where[]=['jobs.jobs_cate3','in',$cid3];
        }
        if (!empty($D['company_id']))
            $where[]=['jobs.company_id','=',intval($D['company_id'])];
        if (!empty($D['jobs_id']))
            $where[]=['jobs.id','=',intval($D['jobs_id'])];
        if(!empty($D['area'])){
            if(!empty($D['area'][0]))
            $where[]=['jobs.jobs_area1','=',intval($D['area'][0])];
            if(!empty($D['area'][1]))
            $where[]=['jobs.jobs_area2','=',intval($D['area'][1])];
            if(!empty($D['area'][2]))
            $where[]=['jobs.jobs_area3','=',intval($D['area'][2])];
        }
        if(!empty($D['app_id'])){
            $where[]=['jobs.app_id','in',$D['app_id']];
        }
        if(!empty($D['top'])&&$D['top']!='all'){
            $where[]=['jobs.top','=',1];
        }
        if(!empty($D['recommend'])&&$D['recommend']!='all'){
            $where[]=['jobs.recommend','=',1];
        }
        if(!empty($D['urgent'])&&$D['urgent']!='all'){
            $where[]=['jobs.urgent','=',1];
        }
        if (!empty($D['is_famous']) && $D['is_famous']!='all')
            $where[]=['c.is_famous','=',1];
        if (!empty($D['vip_level']))
            $where[]=['user_vip.company_vip_level','in',$D['vip_level']];
        $sort='jobs.urgent desc,jobs.top desc,jobs.refresh_time desc,jobs.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='jobs.update_time desc,jobs.id desc';
                    break;
                case 'recommend':
                    $sort='jobs.urgent desc,jobs.top desc,jobs.recommend desc,jobs.refresh_time desc,jobs.id desc';
                    break;
                case 'rand':
                    $sort='jobs.refresh_time desc,jobs.id rand()';
                    break;
            }
        }
        $Field=[
            'jobs.id,jobs.title,jobs.update_time,jobs.create_time,jobs.salary_min,jobs.salary_max,jobs.salary_year,jobs.jobs_welfare,jobs.company_id,jobs.refresh_time,jobs.view,jobs.top,jobs.recommend,jobs.urgent,jobs.number_of_recruiters',
            'contacts.contacts,contacts.contacts_type,contacts.contacts_address',
            'c.title as company_name,c.stitle as scompany_name,c.logo',
            'industry.title as industry',
            'jobs_cate.title as jobs_cate',
            'province.title as jobs_province,city.title as jobs_city,area.title as jobs_area',
            'size_type.title as size_type',
            'education.title as education',
            'desc.jobs_desc',
            'exp_level.title as exp_level'
        ];
        if(config('xy_company.jobs_view_status'))
            $where[]=['jobs.examine','=',1];
        if(config('xy_company.is_forceattestation'))
            $where[]=['c.attestation','=',3];
        $JobsModel=JobsModel::alias('jobs')
            ->where(['jobs.status'=>1])
            ->whereNull('jobs.delete_time')
            ->where($where);
            if(!empty($D['time'])&&count($D['time'])===2){
                $JobsModel->whereTime('jobs.create_time','between',[$D['time'][0]/1000,$D['time'][1]/1000]);
            }
        $qrsize=new \stdClass;
        $qrsize->size=140;
        $Data=$JobsModel->where(['size_type.alias'=>'company/size_type'])
            ->where(['education.alias'=>'jobs/education_level'])
            ->where(['exp_level.alias'=>'jobs/exp_level'])
            ->join('company c','c.id=jobs.company_id')
            ->join('user_vip user_vip','user_vip.uid=c.uid')
            ->join('company_industry industry','industry.id=c.industry_id')
            ->join('jobs_cate jobs_cate','jobs_cate.id=jobs.jobs_cate3')
            ->join('status_alias size_type','size_type.value=c.size_type')
            ->join('status_alias education','education.value=jobs.education_level')
            ->join('status_alias exp_level','exp_level.value=jobs.exp_level')
            ->join('area province','province.id = jobs.jobs_area1')
            ->join('area city','city.id = jobs.jobs_area2')
            ->join('area area','area.id = jobs.jobs_area3')
            ->join('jobs_desc desc','desc.jobs_id = jobs.id')
            ->join('jobs_contacts contacts','contacts.jobs_id=jobs.id','LEFT')
            ->order($sort)
            ->field(implode(',',$Field))->paginate($D['sum'])
            ->each(function($item, $key)use($qrsize){
                $item->friendly_create_time=friendly_time($item['refresh_time'],'friendly');
                $item->welfare=$item['jobs_welfare']?StatusAliasModel::where(['alias'=>'company/corporate_welfare'])->where('value','in',explode(',',$item['jobs_welfare']))->column('title'):[];
                $item->logo=$item['logo']?config('web.imgurl').$item['logo']:config('web.imgurl').config('xy_default_avatar.company_logo');
                $item->number_of_recruiters=$item->number_of_recruiters?$item->number_of_recruiters.'人':'若干';
                $qrcode=PostersController::CreateJobsQRCode($item,$qrsize);
                if($qrcode)
                $item->qrcode=config('web.imgurl').$qrcode;
                if ($item->contacts_type){
                    $company_content=CompanyContentModel::alias('content')->where(['content.cid'=>$item->company_id])->field('content.contacts')
                    ->find();
                    $item->contacts=$company_content->contacts;
                    $item->address=$company_content->contacts_address;
                }
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
            });
        return $Data;
    }
}
